#include "RenderUnit.h"

namespace Display
{

	RenderUnit::RenderUnit( void )
	{
		meshPtr = nullptr;
	}

	RenderUnit::~RenderUnit( void )
	{
		if(meshPtr != nullptr)
			delete meshPtr;

		for(it = texPairs.begin();it != texPairs.end();++it)
		{
			delete (*it)->texturePtr;
		}

		texPairs.clear();
	}

	RenderUnit * RenderUnit::Create( ID3D11Device * device )
	{
		RenderUnit * pack = new RenderUnit();
		pack->SetDevice(device);

		return pack;
	}

	void RenderUnit::Destroy( RenderUnit * pack )
	{
		if(pack != nullptr)
		{
			delete pack;
			pack = nullptr;
		}
	}

	Mesh * RenderUnit::GetMesh()
	{
		return (Mesh*) meshPtr->Get();
	}

	void RenderUnit::SetMesh(ResourcePtr * meshPtr)
	{
		if(this->meshPtr != meshPtr)
		{
			if(this->meshPtr != nullptr)
				delete this->meshPtr;

			this->meshPtr = meshPtr;
		}
	}

	bool RenderUnit::TexTypeLoaded( TextureType type )
	{
		for(it = texPairs.begin();it != texPairs.end();++it)
		{
			if((*it)->type == type)
				return true;
		
		}
		return false;
	}
	 
	Texture * RenderUnit::GetTextureByType( TextureType type )
	{
		if(TexTypeLoaded(type) == false)
			return nullptr;

		for(it = texPairs.begin();it != texPairs.end();++it)
		{
			if((*it)->type == type)
			{
				return (Texture*)(*it)->texturePtr->Get();
			}
		}

		return nullptr;
	}

	void RenderUnit::SetTextureByType( TextureType type,ResourcePtr * tex )
	{
		bool exist = false;
		for(it = texPairs.begin();it != texPairs.end();++it)
		{
			if((*it)->type == type)
			{
				Texture_TypePair * pair = (*it);
				if(pair->texturePtr != tex)
				{
					delete pair->texturePtr;
					pair->texturePtr = tex;
				}

				exist = true;
				break;
			}
		}

		if(exist == false)
		{
			Texture_TypePair * pair = new Texture_TypePair();
			pair->texturePtr = tex;
			pair->type = type;

			texPairs.push_back(pair);
		}
	}

}